import cv2
import numpy as np

# 读取图片
img = cv2.imread('6.jpg')

# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 应用Canny边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)

# 查找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 近似轮廓并检查是否为四边形
for contour in contours:
    # 近似轮廓
    perimeter = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)

    # 如果是四边形
    if len(approx) == 4:
        # 获取四边形的四个顶点
        pts = approx.reshape(4, 2)
        pts_ordered = pts[np.argsort(pts[:, 0])]

        # 获取透视变换矩阵
        M = cv2.getPerspectiveTransform(pts_ordered, np.float32([[0, 0], [max(pts_ordered[:, 0]), 0], [max(pts_ordered[:, 0]), max(pts_ordered[:, 1])], [0, max(pts_ordered[:, 1])]]))

        # 进行透视变换
        warped = cv2.warpPerspective(img, M, (int(max(pts_ordered[:, 0])), int(max(pts_ordered[:, 1]))))

        # 显示并保存结果
        cv2.imshow('Warped', warped)
        cv2.imwrite('warped.jpg', warped)
        cv2.waitKey(0)
        break

cv2.destroyAllWindows()